package org.example;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo {
    static class TestObject{

    }
    //线程相关的变量,为每一个线程分配一个同类型变量
    static ThreadLocal<TestObject> tl = new ThreadLocal<>();
    public static void main(String[] args) throws IOException {

        new Thread(()->{
            try {
                Thread.currentThread().setName("thread 1");
                TimeUnit.SECONDS.sleep(2);
            }catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            System.out.println(tl.get() + " " + Thread.currentThread().getName()); //null
        }).start();


        new Thread(()->{
            try {
                Thread.currentThread().setName("thread 2");
                TimeUnit.SECONDS.sleep(1);
            }catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            tl.set(new TestObject());
            System.out.println(tl.get() + " " +Thread.currentThread().getName());
        }).start();
    }
}
